package com.weikuang.fareast.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.weikuang.fareast.R;
import com.weikuang.fareast.adapter.AddListAdapter;
import com.weikuang.fareast.bean.AddListEvent;
import com.weikuang.fareast.bean.Count1Bean;
import com.weikuang.fareast.bean.HotelBean;
import com.weikuang.fareast.bean.OfficeBean;
import com.weikuang.fareast.bean.TeamBean;
import com.weikuang.fareast.bean.UserBean;
import com.weikuang.fareast.http.MainHttp;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.dlc.commonlibrary.okgo.rx.OkObserver;
import cn.dlc.commonlibrary.ui.widget.CommonItemView;
import cn.dlc.commonlibrary.ui.widget.TitleBar;
import cn.dlc.commonlibrary.ui.widget.popup.CommonPopupList;
import cn.dlc.commonlibrary.utils.TimeFormats;
import cn.dlc.commonlibrary.utils.ToastUtil;
import cn.dlc.commonlibrary.utils.rv_tool.RecyclerViewUtil;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

//录入列表
public class AddListActivity extends BaseActivity implements OnDateSetListener {


    @BindView(R.id.mTitleBar)
    TitleBar mTitleBar;
    @BindView(R.id.tv_hospital)
    TextView tvHospital;
    @BindView(R.id.drop_hospital)
    FrameLayout dropHospital;
    @BindView(R.id.item_hospital)
    CommonItemView itemHospital;
    @BindView(R.id.tv_group)
    TextView tvGroup;
    @BindView(R.id.drop_group)
    FrameLayout dropGroup;
    @BindView(R.id.item_group)
    CommonItemView itemGroup;
    @BindView(R.id.tv_offic)
    TextView tvOffic;
    @BindView(R.id.drop_offic)
    FrameLayout dropOffic;
    @BindView(R.id.item_offic)
    CommonItemView itemOffic;
    @BindView(R.id.start_time)
    CommonItemView startTime;

    @BindView(R.id.btn_search)
    Button btnSearch;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;


    private CommonPopupList mHospitalPopup, mOfficPopup, mGropPopup,mPersonPopup;
    private List<HotelBean.DataBean> mHospitalList;
    private List<OfficeBean.DataBean> mOfficList;
    private List<TeamBean.DataBean> mTeamList;
    private String offic_id = "",hotel_id = "",team_id="";
    private AddListAdapter mCheckListAdapter;

    TimePickerDialog mDialogYearMonthDay;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_list;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initView();
        InitRecyclerView();
       // getHotel();
        mDialogYearMonthDay = new TimePickerDialog.Builder()
                .setType(Type.YEAR_MONTH_DAY)
                .setCallBack(this)
                .build();
    }


    @OnClick({R.id.drop_hospital, R.id.drop_group, R.id.drop_offic,R.id.btn_search,R.id.start_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.drop_hospital:
                //mHospitalPopup.showAsDropDown(view);
                tvHospital.setText("");
                hotel_id = "";
                startActivityForResult(new Intent(getActivity(),HotelActivity.class),2001);
                break;
            case R.id.drop_group:
                mGropPopup.showAsDropDown(view);
                break;
            case R.id.drop_offic:
                mOfficPopup.showAsDropDown(view);
                break;

            case R.id.btn_search:
                checkQuery();
                break;
            case R.id.start_time:
                mDialogYearMonthDay.show(getSupportFragmentManager(), "year_month_day");
                break;
        }
    }

    private void initView() {
        mHospitalPopup = CommonPopupList.newBuilder(this)
                .setWidthEquals(dropHospital)
                .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                    @Override
                    public void onSelectItem(CommonPopupList popup, String item, int position) {
                        popup.dismiss();
                        tvHospital.setText(item);

                        if (mHospitalList != null) {
                            // getOffice(mHospitalList.get(position).id);
                            hotel_id = mHospitalList.get(position).id;
                            getTeam(mHospitalList.get(position).id);
                        }

                    }
                })
                .build();
        mOfficPopup = CommonPopupList.newBuilder(this)
                .setWidthEquals(dropOffic)
                .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                    @Override
                    public void onSelectItem(CommonPopupList popup, String item, int position) {
                        popup.dismiss();
                        tvOffic.setText(item);
                        if (mOfficList != null) {

                            offic_id = mOfficList.get(position).id;
                        }

                    }
                })
                .build();
        mGropPopup = CommonPopupList.newBuilder(this)
                .setWidthEquals(dropGroup)
                .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                    @Override
                    public void onSelectItem(CommonPopupList popup, String item, int position) {
                        popup.dismiss();
                        tvGroup.setText(item);
                        if (mTeamList != null) {
                            team_id = mTeamList.get(position).id;
                            getOffice(mTeamList.get(position).id);
                        }

                    }
                })
                .build();

    }

    private void InitRecyclerView() {
        mCheckListAdapter = new AddListAdapter();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        RecyclerViewUtil.setDefaultDivider(mRecyclerView, linearLayoutManager);
        mRecyclerView.setAdapter(mCheckListAdapter);
        mCheckListAdapter.setOnItemClickListener(new AddListAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, Count1Bean.DataBean data, int position) {
                mCheckListAdapter.setNewData(null);
                Intent mIntent = new Intent(AddListActivity.this,AddChangActivity.class);
                mIntent.putExtra("data",data);
                startActivityForResult(mIntent,2005);
//                Intent mIntent = new Intent(CheckListActivity.this,ChangeDataActivity.class);
//                mIntent.putExtra("data",data);
//                startActivity(mIntent);
            }
        });

    }


    private void getOffice(String team_id) {
        if (TextUtils.isEmpty(hotel_id)){
            ToastUtil.show(getActivity(),"请选择医院");
            return;
        }
        MainHttp.get().getOffice(hotel_id,team_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<OfficeBean>() {
                    @Override
                    public void onSuccess(OfficeBean officeBean) {
                        List<String> datas = new ArrayList<>();
                        mOfficList = officeBean.data;
                        for (OfficeBean.DataBean bean : officeBean.data) {
                            datas.add(bean.title);
                        }
                        mOfficPopup.setData(datas);
                    }

                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(getActivity(), message);
                    }
                });
    }

    private void getTeam(String hotel_id) {

        MainHttp.get().getTeam(hotel_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<TeamBean>() {
                    @Override
                    public void onSuccess(TeamBean officeBean) {
                        List<String> datas = new ArrayList<>();
                        mTeamList = officeBean.data;
                        for (TeamBean.DataBean bean : officeBean.data) {
                            datas.add(bean.title);
                        }
                        mGropPopup.setData(datas);
                    }

                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(getActivity(), message);
                    }
                });
    }

    private void checkQuery() {

        String start = startTime.getContentText();
        if (TextUtils.isEmpty(start)|| start.contains("请")){
            start = "";
        }

        showWaitingDialog("请等待",true);
        MainHttp.get().count1(hotel_id,team_id,offic_id,start,"")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<Count1Bean>() {
                    @Override
                    public void onSuccess(Count1Bean officeBean) {
                        dismissWaitingDialog();
                        mCheckListAdapter.setNewData(officeBean.data);
                    }

                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(getActivity(), message);
                        dismissWaitingDialog();
                    }
                });
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(AddListEvent event) {
        checkQuery();
    }
    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        startTime.setContent(TimeFormats.formatDateTime1(timePickerView.getCurrentMillSeconds()));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == 3 && data != null) {
            UserBean.DataBean mUserdata = (UserBean.DataBean) data.getSerializableExtra("data");

        }else  if (resultCode == 4 && data != null) {
            HotelBean.DataBean mUserdata = (HotelBean.DataBean) data.getSerializableExtra("data");
            if (mUserdata != null) {
                tvHospital.setText(mUserdata.title);
                hotel_id = mUserdata.id;
                getTeam(hotel_id);
            }
        }
    }
}
